package com.insta.achilog.dal;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Connexion {

	private final static String chaineConnection = "jdbc:hsqldb:file:src/main/resources/data/librairie_db;shutdown=true";
	
	public static Connection getInitConnexion () {
		
		Connection c = null;
		
		try {
			Class.forName("org.hsqldb.jdbcDriver").newInstance();
			// System.out.println(new File("toto.txt").getAbsolutePath());

			Connection connexion = DriverManager.getConnection(
					chaineConnection, "root", "");
			
			c = connexion;
			
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return c;

	}
	
	public ResultSet ExecuteSelectQuery (String Query){
		Statement statement;
		try {

			Connection connection = getInitConnexion();
			statement =  connection.createStatement();
			final ResultSet resultat = statement.executeQuery(Query);
			
			closeConnection(connection);
			return resultat;

		} catch (final SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}
	
	public Boolean ExecuteUpdateQuery (String Query){
		Statement statement;
		try {

			Connection connection = getInitConnexion();
			statement =  connection.createStatement();
			statement.executeUpdate(Query);
			
			closeConnection(connection);
			
			return true;

		} catch (final SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return false;
	}
	
	
	public Boolean ExecuteInsertQuery (String Query){
		Statement statement;
		try {

			Connection connection = getInitConnexion();
			statement =  connection.createStatement();
			statement.execute(Query);
			
			closeConnection(connection);
			return true;

		} catch (final SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return false;
	}
	
	public Boolean ExecuteDeleteQuery (String Query){
		Statement statement;
		try {

			Connection connection = getInitConnexion();
			statement =  connection.createStatement();
			statement.execute(Query);
			
			closeConnection(connection);
			
			return true;

		} catch (final SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return false;
	}
	
	
	public static void closeConnection(Connection c){
		try {
			c.close();
			//System.out.println("FINISH");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
